(function () {
    /*
     * source:https://gitee.com/sin911/export_to_excel
     */
    function WsjExportExcel(option) {
        if (!option.data) {
            alert('缺少必填属性data')
            return
        }

        var defaultOption = {
            fileName: dataFormat(),
            sheetName:'sheet'
        }

        var __option = Object.assign({}, defaultOption, option)
        var template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><meta charset="UTF-8"><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>'+__option.sheetName+'</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml></head><body>{htmlData}</body></html>'
        var Excel_URL = 'data:application/vnd.ms-excel;base64,'
        var __content = ''
        if (typeof __option.data === 'string') {
            var ele = document.querySelector(__option.data)
            __content = template.replace("{htmlData}", ele.outerHTML)
        } else {
            var arr = []
            arr.push('<table>')
            __option.data.forEach(function (v, k) {
                arr.push('<tr>')
                v.forEach(function (vv, kk) {
                    var processFormat = ''
                    if (/^(-)?\d+(\.\d+)?$/.test(vv) && vv.toString().length >= 12) {
                        processFormat = 'style="text-align:right;mso-number-format:\'\@\';"'
                    }
                    arr.push('<td ' + processFormat + '>' + vv + '</td>')
                })
                arr.push('</tr>')
            })
            arr.push('</table>')
            __content = template.replace("{htmlData}", arr.join(''))
        }
        var aEle = document.createElement('a')
        aEle.href = Excel_URL + window.btoa(unescape(encodeURIComponent(__content)))
        aEle.download = __option.fileName + ".xls"
        aEle.click()

        function dataFormat() {
            var d = new Date()
            return ('' + d.getFullYear() + '-' + (addZero(d.getMonth() + 1)) + '-' + addZero(d.getDate()) + ' ' + addZero(d.getHours()) + '_' + addZero(d.getMinutes()) + '_' + addZero(d.getSeconds()))
        }
        function addZero(num) {
            return num < 10 ? '0' + num : num
        }
}
window.WsjExportExcel = WsjExportExcel
})()